// src/routes/index.tsx
import { lazy, Suspense, FC } from "react";
import { useRoutes } from "react-router-dom";
import { ShopOutlined } from "@ant-design/icons";
import type { XRoutes } from "./types";

import Loading from "@comps/Loading";

const HospitalSet = lazy(() => import("@pages/HospitalSet"));
const HospitalList = lazy(() => import("@pages/HospitalList"));
const HospitalSetAddOrUpdate = lazy(
  () => import("@pages/HospitalSet/comp/HospitalSetAddOrUpdate")
);
const HospitalSchedule = lazy(
  () => import("@pages/HospitalList/comp/HospitalSchedule")
);
const HospitalShow = lazy(
  () => import("@pages/HospitalList/comp/HospitalShow")
);

const load = (Comp: FC) => {
  return (
    // 因为路由懒加载，组件需要一段网络请求时间才能加载并渲染
    // 在组件还未渲染时，fallback就生效，来渲染一个加载进度条效果
    // 当组件渲染完成时，fallback就失效了
    <Suspense fallback={<Loading />}>
      {/* 所有lazy的组件必须包裹Suspense组件，才能实现功能 */}
      <Comp />
    </Suspense>
  );
};

// 注意: 当前项目中这个路由表一表二用:
// 1. 正常去渲染前端路由规则
// 2. 使用里面/syt去动态渲染左侧导航按钮
const routes: XRoutes = [
  {
    path: "/hospitalset",
    meta: { title: "医院设置" },
    element: load(HospitalSet),
  },
  {
    path: "/hospitalset/add",
    meta: { title: "添加医院" },
    element: load(HospitalSetAddOrUpdate),
    hidden: true, // 当前路由不渲染在左侧导航中
  },
  {
    path: "/hospitalset/update/:id",
    meta: { title: "修改医院" },
    element: load(HospitalSetAddOrUpdate),
    hidden: true, // 当前路由不渲染在左侧导航中
  },
  {
    path: "/hospitallist",
    meta: { title: "医院列表" },
    element: load(HospitalList),
  },
  {
    path: "/hospitallist/schedule",
    meta: { title: "医院排班" },
    element: load(HospitalSchedule),
    hidden: true,
  },
  {
    path: "/hospitallist/show/:id",
    meta: { title: "医院详情" },
    element: load(HospitalShow),
    hidden: true,
  },
];

// 渲染路由
// 注意：首字母必须大写
export const RenderRoutes = () => {
  // react-router-dom的新增语法。不用自己遍历了，它帮我们遍历生成
  return useRoutes(routes);
};

// 找到要渲染成左侧菜单的路由
export const findSideBarRoutes = () => {
  const currentIndex = routes.findIndex((route) => route.path === "/syt");
  return routes[currentIndex].children as XRoutes;
};

export default routes;
